"""
    TorrentBrowser plugin for XBMC
    Copyright (C) 2011-2012 Markus Langenoja
    
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
    Function [TBDownload]
    -------------------
    * downloadTorrent(url, title) - Downloads url and names it title.torrent, then puts it in __dlpath__
"""        
import sys
import TBTools

class TBDownload(TBTools.TBTools):
    __deb__ = sys.modules[ "__main__" ].__deb__
    __plugin__ = sys.modules[ "__main__" ].__plugin__
    __settings__ = sys.modules[ "__main__" ].__settings__
    __web__ = sys.modules[ "__main__" ].__web__
    
    __dlpath__ = __settings__.getSetting('dlpath')
    
    def downloadTorrent(self, url, title):
#        # Imports TBWeb here because it is a delay of 4 seconds loading LWPCookieJar()
#        import TBWeb
#        __web__ = TBWeb.TBWeb
        
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBDownload::Initiated torrent file download for '+title
        # Cleans title to get clean filename & build download path
        torrentName = self.cleanString(title)
        __torrent__ = self.__dlpath__ + '/' + torrentName + '.torrent'
        print 'Torrent Path: ' + __torrent__
        # Download the torrent into memory
        __data__ = self.__web__.loginOpen(url)
        # Initiate filewrite and write the torrent from memory
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBDownload::Writing to file: '+__torrent__
        f = open(__torrent__, 'wb')
        f.write(__data__)
        f.close()
